{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE RecordWildCards   #-}
{-# LANGUAGE ScopedTypeVariables#-}
{-# LANGUAGE FlexibleContexts#-}
module App.UserCenter.UserTypes (Account,parseAccount,Password,parsePassword,ConstLenText,parseConstLenText) where
import qualified Data.Text as T
import App.Common.Types
import Text.Regex.TDFA
import Text.Regex.TDFA.Text
import Data.Monoid
import Control.Monad.Except

isMatch rex str = matchTest m str  
  where m::Regex = makeRegex rex

isNotMatch rex str = not $ isMatch rex str 

isAccount::T.Text -> Bool
isAccount  = isMatch ("^[a-zA-Z0-9]{6,15}$"::T.Text)

data Account = Account T.Text deriving (Show,Eq)

parseAccount::(MonadError T.Text m) => T.Text -> m Account
parseAccount s = if isAccount s then return $ Account s else throwError "用户名格式错误"

instance ShowText Account where
    showText (Account txt) = txt
--------------------------------------------

data ConstLenText = ConstLenText T.Text Int  deriving (Show,Eq)

parseConstLenText::(MonadError T.Text m) => T.Text -> (Int -> Int->Bool) -> Int -> T.Text  -> m ConstLenText
parseConstLenText s cpf l ts = if (cpf l).T.length $ s then return $ ConstLenText s l else throwError ts

instance ShowText ConstLenText where
    showText (ConstLenText txt _) = txt

--------------------------------------------
type Password  = ConstLenText

parsePassword::(MonadError T.Text m) => T.Text -> m Password
parsePassword s = parseConstLenText s (<=) 6  "密码必须大于等于6位"

 ----------------------------------------------
isEmail::T.Text -> Bool
isEmail = isMatch ("^[a-zA-Z0-9_.+]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+$"::T.Text) 

isPhone::T.Text -> Bool
isPhone = isMatch ("^[1][3,4,5,7,8][0-9]{9}$"::T.Text) 
